import { ipcRenderer, contextBridge, shell } from 'electron'

// --------- Expose some API to the Renderer process ---------
contextBridge.exposeInMainWorld('ipcRenderer', {
  on(channel: string, func: (...args: any[]) => void) {
    const listener = (_event: any, ...args: any[]) => func(...args)
    ipcRenderer.on(channel, listener)
    return () => ipcRenderer.removeListener(channel, listener)
  },
  off(channel: string, func: Function) {
    ipcRenderer.removeListener(channel, func as any)
  },
  send(channel: string, ...args: any[]) {
    ipcRenderer.send(channel, ...args)
  },
  invoke(channel: string, ...args: any[]) {
    return ipcRenderer.invoke(channel, ...args)
  }
})

contextBridge.exposeInMainWorld('electronAPI', {
  // 卡片操作API
  loadCards: () => ipcRenderer.invoke('loadCards'),
  saveCard: (card: any) => ipcRenderer.invoke('saveCard', card),
  deleteCard: (cardId: string) => ipcRenderer.invoke('deleteCard', cardId), // Changed from number to string
  
  // 垃圾站操作API
  getTrashCards: (page: number, pageSize: number) => ipcRenderer.invoke('getTrashCards', page, pageSize),
  moveCardToTrash: (cardId: string) => ipcRenderer.invoke('moveCardToTrash', cardId),
  restoreCardFromTrash: (cardId: string) => ipcRenderer.invoke('restoreCardFromTrash', cardId),
  permanentlyDeleteCard: (cardId: string) => ipcRenderer.invoke('permanentlyDeleteCard', cardId),
  emptyTrash: () => ipcRenderer.invoke('emptyTrash'),
  
  // 配置操作API
  loadConfig: () => ipcRenderer.invoke('loadConfig'),
  saveConfig: (config: any) => ipcRenderer.invoke('saveConfig', config),
  
  // 文件夹选择API
  selectFolder: () => ipcRenderer.invoke('selectFolder'),
  
  // 获取默认路径API
  getDefaultPath: () => ipcRenderer.invoke('getDefaultPath'),
  getDefaultTrashPath: () => ipcRenderer.invoke('getDefaultTrashPath'),
  
  // 日期时间格式化API
  getCurrentDateTime: (fieldType: string = 'general') => ipcRenderer.invoke('getCurrentDateTime', fieldType),
  
  // 在应用内打开链接
  openInternalWindow: (url: string) => ipcRenderer.invoke('open-internal-window', url)
})

// 暴露shell API以在系统浏览器中打开URL
contextBridge.exposeInMainWorld('electronShell', {
  openExternal: (url: string) => shell.openExternal(url),
  // 添加备选方案，通过IPC通道打开URL
  openExternalViaIpc: (url: string) => ipcRenderer.invoke('open-external-url', url)
})
